package com.swl.small.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.swl.common.constant.ProductConstant;
import com.swl.common.to.SkuReductionTo;
import com.swl.common.to.SpuBoundsTo;
import com.swl.common.to.es.SkuEsModel;
import com.swl.common.utils.R;
import com.swl.small.product.entity.AttrEntity;
import com.swl.small.product.entity.BrandEntity;
import com.swl.small.product.entity.CategoryEntity;
import com.swl.small.product.entity.ProductAttrValueEntity;
import com.swl.small.product.entity.SkuImagesEntity;
import com.swl.small.product.entity.SkuInfoEntity;
import com.swl.small.product.entity.SkuSaleAttrValueEntity;
import com.swl.small.product.entity.SpuInfoDescEntity;
import com.swl.small.product.feign.CouponFeignService;
import com.swl.small.product.feign.SearchFeiginService;
import com.swl.small.product.feign.WareFeignService;
import com.swl.small.product.service.AttrService;
import com.swl.small.product.service.BrandService;
import com.swl.small.product.service.CategoryService;
import com.swl.small.product.service.ProductAttrValueService;
import com.swl.small.product.service.SkuImagesService;
import com.swl.small.product.service.SkuInfoService;
import com.swl.small.product.service.SkuSaleAttrValueService;
import com.swl.small.product.service.SpuImagesService;
import com.swl.small.product.service.SpuInfoDescService;
import com.swl.small.product.vo.Attr;
import com.swl.small.product.vo.BaseAttrs;
import com.swl.small.product.vo.Bounds;
import com.swl.small.product.vo.SkuHasStockVo;
import com.swl.small.product.vo.Skus;
import com.swl.small.product.vo.SpuSaveVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swl.common.utils.PageUtils;
import com.swl.common.utils.Query;

import com.swl.small.product.dao.SpuInfoDao;
import com.swl.small.product.entity.SpuInfoEntity;
import com.swl.small.product.service.SpuInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeiginService searchFeiginService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSupInfo(SpuSaveVo vo) {
        //1.保存spu基本信息 pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);
        //2.保存spu的描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        descEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);
        //3.保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(infoEntity.getId(), images);
        //4.保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(item.getAttrId());
            AttrEntity attrEntity = attrService.getById(item.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            productAttrValueEntity.setSpuId(infoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(productAttrValueEntities);
        //5.保存spu的积分信息 small->sms -> sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(infoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }
        //6.保存当前spu对应的所有sku信息
        List<Skus> skus = vo.getSkus();
        if (!CollectionUtils.isEmpty(skus)) {
            skus.forEach(item -> {
                //6.1sku的基本信息 pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(
                        item.getImages().stream().filter(img -> img.getDefaultImg() == 1).findAny().get().getImgUrl());
                skuInfoService.saveSkuInfo(skuInfoEntity);
                //6.2sku的图片信息 pms_sku_images
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(i -> !StringUtils.isEmpty(i.getImgUrl())).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);
                //6.3sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                //6.4sku的优惠、满减等信息 small_sms -> sms_sku_ladder,sms_sku_full_reduction,
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal(0)) == 1) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }


    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        this.baseMapper.insert(infoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(w -> w.eq("id", key).or().like("spu_name", key));
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {

        List<SkuEsModel> upProducts = new ArrayList<>();

        //组装需要的数据
        //查询当前sku的所有可以被检索的规格属性
        List<ProductAttrValueEntity> basteAttrs = productAttrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = basteAttrs.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> searchAttrsIds = attrService.selectSearchAttrs(attrIds);
        Set<Long> idSet = new HashSet<>(searchAttrsIds);
        List<SkuEsModel.Attrs> attrs = new ArrayList<>();
        attrs = basteAttrs.stream().filter(item -> idSet.contains(item))
                .map(item -> {
                    SkuEsModel.Attrs sas = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(item, sas);
                    return sas;
                }).collect(Collectors.toList());

        //查出当前spuid对应的所有sku信息、品牌名
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        //hasStock向库存系统发送请求查询是否有库存
        Map<Long, Boolean> map = null;
        try {
            List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
            R r = wareFeignService.getSkusHasStock(skuIdList);
            //泛型转换
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<>() {
            };
            map = r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常，原因：{}", e);
        }
//            esModel.setHasStock();
        //封装每个sku的信息
        List<SkuEsModel.Attrs> finalAttrs = attrs;
        Map<Long, Boolean> finalMap = map;
        List<SkuEsModel> skuEsModels = skus.stream().map(skuId -> {
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(skuId, esModel);
            esModel.setSkuPrice(skuId.getPrice());
            esModel.setSkuImg(skuId.getSkuDefaultImg());
            //设置是否有库存
            if (finalMap != null) {
                esModel.setHasStock(finalMap.get(skuId));
            } else {
                esModel.setHasStock(true);
            }
            //hotScore热度评分，刚上架的商品设为0->未实现
            esModel.setHotScore(0L);
            //查询品牌和分类的名字
            BrandEntity brand = brandService.getById(esModel.getBrandId());
            esModel.setBrandName(brand.getName());
            esModel.setBrandImg(brand.getLogo());
            CategoryEntity category = categoryService.getById(esModel.getCatalogId());
            esModel.setCatalogName(category.getName());
            esModel.setAttrs(finalAttrs);
            return esModel;
        }).collect(Collectors.toList());

        //将数据发送给es保存：small-search
        R r = searchFeiginService.productStatusUp(skuEsModels);
        if (r.getCode() == 0) {
            //修改当前spu的状态为已上架
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            //重复调用、接口幂等性等问题

        }
    }


}